<template>
  <div>
    <div>
      <el-row style="display: flex; align-items: center;">
        <el-col :span="3">关键字查询：</el-col>
        <el-col :span="8"> 
          <div style="position: relative;">
            <el-input
              id="tipinput" style="width: 90%;"
              v-model="input"
              placeholder="请输入你要查找的关键词"
            ></el-input>
            <div id="tipoutput"></div>
        </div>
      </el-col>
        <el-col :span="3">选择的位置：</el-col>
        <el-col :span="10"><span v-text="dataForm.kqLocation"></span></el-col>
      </el-row>
     
      
    </div>
    <div id="container"></div>
  </div>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";

export default {
  name: "map-view",
  props: {
    longitude:{
        type : Number,
      },
      latitude:{
        type : Number,
      },
    },
  data(){
  return {
      loading: false,
      visible: true,
      isDetail: false,
      dataForm: {
        kqName: undefined,
        kqLocation: undefined,
        kqLongitude: undefined,
        kqLatitude: undefined,
      },
      rules: {},
      input: "",
      map: null,
      auto: null,
      placeSearch: null,
      lnglat: [],
      markers: [],
      position: {},
    };
  },
  mounted() {

    window._AMapSecurityConfig = {
      securityJsCode: "6b7bf54077ccb6b8a34bacd018cb74f5",
    };
    this.initAMap();
  },
  unmounted() {
    this.map?.destroy();
  },
  created(){
    this.dataForm.kqLongitude = this.longitude 
    this.dataForm.kqLatitude = this.latitude
  },
  methods: {

    initAMap() {
      // console.log('propslongitude',this.dataForm.longitude )
      //   console.log('propslatitude',this.dataForm.latitude)
      let centerLen = [this.dataForm.kqLongitude?this.dataForm.kqLongitude:116.397428, this.dataForm.kqLatitude?this.dataForm.kqLatitude:39.90923];
      AMapLoader.load({
        key: "ba428a103f8e0e890f9ed983f50ec9aa", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.AutoComplete", "AMap.PlaceSearch", "AMap.Geocoder"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
         resizeEnable: true,
      })
        .then((AMap) => {
      //     const that = this;
      //  that.map = new AMap.Map("container",{  //设置地图容器id
      //    viewMode:"3D",    //是否为3D地图模式
      //    zoom:12,          //初始化地图级别
      //  });
        this.map = new AMap.Map("container",{
          viewMode: "3D", //  是否为3D地图模式
            zoom: 18, // 初始化地图级别
            center: centerLen, //中心点坐标
            resizeEnable: true,

        });
        this.setMarker(centerLen);
        // 关键字查询
        this.searchMap();
          // 监听鼠标点击事件
        this.map.on("click", this.clickMapHandler);
        })
        .catch((e) => {
          console.log(e);
        });
    },
     // 关键字查询
     searchMap () {
      // 搜索框自动完成类
      this.auto = new AMap.AutoComplete({
        input: "tipinput", // 使用联想输入的input的id
        output: "tipoutput",
        closeResultOnScroll:false
      });
      // 当选中某条搜索记录时触发
      this.auto.on("select", this.selectSite);
      //构造地点查询类
      this.placeSearch = new AMap.PlaceSearch({
        map: this.map,
      });
      
    },
    //选中查询出的记录
  selectSite (e) {
      if (e.poi.location) {
        // this.lnglat = [e.poi.location.lng, e.poi.location.lat];
        this.placeSearch.setCity(e.poi.adcode);
        this.placeSearch.search(e.poi.name); //关键字查询
        let geocoder = new AMap.Geocoder({});
        let that = this;
        geocoder.getAddress(this.lnglat, function (status, result) {
          if (status === "complete" && result.regeocode) {
            that.province = result.regeocode.addressComponent.province;
            that.city = result.regeocode.addressComponent.city;
            //自己想要赋的值，根据自己的做修改
            that.$set(that.form, "province", that.province);
            that.$set(that.form, "city", that.city);
            that.$set(that.form, "address", e.poi.name);
            that.$set(
              that.form,
              "coordinate",
              e.poi.location.lng + "," + e.poi.location.lat
            ); //纬度，经度
            
          } else {
          }
          that.setMarker([e.poi.location.lng , e.poi.location.lat]);
          that.dataForm.kqLongitude = e.poi.location.lng;
          that.dataForm.kqLatitude = e.poi.location.lat;
        });
      } else {
        this.$message.error("查询地址失败，请重新输入地址");
      }
    },
    
    /**
     * 将选择位置信息保存到父级
     */
    sendUpdatedData() {
      this.$emit('selectPostion', this.dataForm.kqLongitude,this.dataForm.kqLatitude,this.dataForm.kqLocation); // 触发自定义事件，将修改后的数据传递给父组件
    },

    // 点击地图事件获取经纬度，并添加标记
    clickMapHandler (e) {
      console.log("afasdfas")
      this.dataForm.kqLongitude = e.lnglat.getLng();
      this.dataForm.kqLatitude = e.lnglat.getLat();
      this.lnglat = [e.lnglat.getLng(), e.lnglat.getLat()];
      this.setMarker(this.lnglat);
      // 点击地图上的位置，根据经纬度转换成详细地址
      let that = this;
 
      this.position = {
        longitude: e.lnglat.getLng(),
        latitude: e.lnglat.getLat(),
        address: that.address,
      };
      
      this.input = that.address; //把查询到的地址赋值到输入框
    },
  //  添加标记
  setMarker (lnglat) {
      console.log('lnglat',lnglat)
      if(this.map){
        this.removeMarker();
        let templateLnglat = [lnglat[0]?lnglat[0]:116.397428, lnglat[1]?lnglat[1]:39.90923]
        let marker = new AMap.Marker({
          position: templateLnglat,
        });
        marker.setMap(this.map);
        this.markers.push(marker);
        this.map.setCenter(templateLnglat)
        let geocoder = new AMap.Geocoder({});
      let that = this;
      geocoder.getAddress(templateLnglat, function (status, result) {
        if (status === "complete" && result.regeocode) {
          that.dataForm.kqLocation = result.regeocode.formattedAddress;
          //更新选择的位置信息
          that.sendUpdatedData()
        } else {
        }
      });
      
    }
    this.input = ""
    },
    // 删除之前后的标记点
    removeMarker () {
        this.map.remove(this.markers);
    },
  },
};
</script>
<style scoped>
#container {
  margin-top: 20px;
  width: 100%;
  height: 450px;
  
}

#tipoutput{
  position: absolute;
  top: 32px !important;
  left: 0 !important;
  z-index: 9999 !important;
  background: white;
  width: 90%;
}

</style>
